package com.fs.zise;

import Tools.ArrayLink;

import java.io.IOException;
import java.text.BreakIterator;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;


import xmlParse.FntInfo;
import xmlParse.FntPaint;
import xmlParse.SAXPersonService;

import Appconst.ZiseLanguage;
import Appconst.GameConst;
import Tools.Animation;
import Tools.AnimationData;
import Tools.BitmapTool;
import Tools.CFPSMaker;
import Tools.GameButton;
import Tools.GameButtonManage;
import Tools.GameWordButton;
import Tools.ToolUtil;
import android.R.integer;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Paint.Align;
import android.graphics.Paint.Style;
import android.graphics.Rect;
import android.graphics.Region;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.AbsoluteLayout;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import audio.GameMedia;

public class GameSurfaceView extends SurfaceView implements
		SurfaceHolder.Callback, Runnable {

	// 控制循环
	private boolean mbLoop = false;
	// 定义SurfaceHolder对象
	private SurfaceHolder mSurfaceHolder = null;
	private Context context = null;
	// private MediaPlayer mediaPlayer = null;
	// private SoundPool soundPoolEffect = null;
	// private int soundeffectXiaoChuID = -100;
	// private boolean isGamePause = false;
	// 画布
	public Canvas canvas = null;
	// 绘图
	public Paint mPaint = null;

	public int iPage = 0;
	public int iClock = 0;
	public Bitmap logoBitmap = null;
	public Bitmap prepareBitmap = null;
	public Bitmap bgMenuBitmap = null;
	public Bitmap bgMenuItem = null;
	public Bitmap bgMenuChoose = null;
	public int gameState = -1;

	public Bitmap cursorBitmap = null;

	HashMap<Integer, Integer> hashMap = new HashMap<Integer, Integer>();

	private Bitmap mapBitmap = null;
	
	
	
	Bitmap FeeBitmap = null;
	Animation playAnimation = null;
	private static long lThreadTime;
	private int SleepTime = 60;

//	GameMap.getSingleInstance() GameMap.getSingleInstance();

	public GameSurfaceView(Context context) {
		super(context);

		this.context = context;
		// 触屏模式获取焦点
		setFocusableInTouchMode(true);
		// 实例化SurfaceHolder
		mSurfaceHolder = this.getHolder();
		// 添加回调
		mSurfaceHolder.addCallback(this);
		this.setFocusable(true);
		gameState = GameConst.STATE_LOGO;

//		GameMap.getSingleInstance() = new GameMap.getSingleInstance()();

		initResource();
	}

	private void initResource() {
			logoBitmap = BitmapTool.getImageFromAssetFile("logo.png");
			prepareBitmap = BitmapTool.getImageFromAssetFile("prepare.png");
			bgMenuBitmap = BitmapTool.getImageFromAssetFile("basebg.png");
			bgMenuItem = BitmapTool.getImageFromAssetFile("menuword.png");
			bgMenuChoose = BitmapTool.getImageFromAssetFile("menuchoose.png");
			FeeBitmap = BitmapTool.getImageFromAssetFile("123.png");
			cursorBitmap = BitmapTool.getImageFromAssetFile("selection.png");
			mapBitmap = BitmapTool.getImageFromAssetFile("gamemap.png");

		// ---------load animal--------//
		// selectionaAnimation =
		// AnimationUtils.loadAnimation(LlkActivity.getActivity(),
		// R.anim.my_alpha_action);

	}

	public ArrayList<Bombs> mBombs = new ArrayList<Bombs>();
	public ArrayList<LaserEmitter> mLaserEmitters = new ArrayList<LaserEmitter>();
	public ArrayList<Mirror> mMirrors = new ArrayList<Mirror>();
	private ArrayList<ApplyTool> arraylistApplyTools = new ArrayList<ApplyTool>();
	
	
	private Bitmap bitmap_bar_tool; //工具条背景不可响应触摸
	private Bitmap bitmap_bar_select_button ;//工具条选择框
	
	private Bitmap bitmap_apply_tools; //可用的工具
	
	private Bitmap bitmap_wordBG ;//显示文字的BUTTON背景框
	
	
//	 private GestureDetector mGestureDetector;  
	
	 //TEST 字库
	 FntPaint fntPaint; 

	private void Init_STATEGAME() {
	//字库
		fntPaint = new FntPaint("我爱祖国天安门我爱共产党!",100,100);
		
		
		
		
		if(GameMap.getSingleInstance().getLevel() == 0)
			GameMap.getSingleInstance().loadMapData("stage_one.dat");
		
		clearAllRescoures();
		
		feeDead = false;
		
		bitmap_apply_tools = BitmapTool.getImageFromAssetFile("applytools.png");
		bitmap_bar_tool = BitmapTool.getImageFromAssetFile("toolbarBG.png");
		bitmap_bar_select_button = BitmapTool.getImageFromAssetFile("buttonKuang.png");
		
		int mirror_DIR_ID = 0;
		int laserEmitter_DIR_ID = 0;
		
		for (short i = 0; i < GameMap.getSingleInstance().zise0_map0_one[GameMap.getSingleInstance().getLevel()].length; i++) {
			for (short j = 0; j < GameMap.getSingleInstance().zise0_map0_one[0].length; j++) {
				if(GameMap.getSingleInstance().zise0_map0_one[i][j] == 18) //炸弹
				{
					mBombs.add(new Bombs(this,i, j).setBOMB_STATE(Bombs.STATE_NONE));
				}
				else if(GameMap.getSingleInstance().zise0_map0_one[i][j] == 38)   	// 镜子
				{
					mMirrors.add(new Mirror(this,i,j,GameMap.getSingleInstance().zise0_map0_mirror_direction[mirror_DIR_ID]));
					mirror_DIR_ID++;
				}
				else if(GameMap.getSingleInstance().zise0_map0_one[i][j] == 28) // 激光发射器
				{
					mLaserEmitters.add(new LaserEmitter(this,i,j,GameMap.getSingleInstance().zise0_map0_laserEmitter_direction[laserEmitter_DIR_ID]));
					laserEmitter_DIR_ID++;
				}
				else if(GameMap.getSingleInstance().zise0_map0_one[i][j] == 86) ////可使用的道具之扳手
				{
					//添加applytool
					arraylistApplyTools.add(new ApplyTool( i, j ,bitmap_apply_tools));
				}
				else if(GameMap.getSingleInstance().zise0_map0_one[i][j] == 85) //锤子
				{
					//添加applytool
					arraylistApplyTools.add(new ApplyTool( i, j ,bitmap_apply_tools));
				}
				else if(GameMap.getSingleInstance().zise0_map0_one[i][j] == 84)//火柴
				{
					//添加applytool
					arraylistApplyTools.add(new ApplyTool( i, j ,bitmap_apply_tools));
				}
				else if(GameMap.getSingleInstance().zise0_map0_one[i][j] == 83)//水桶
				{
					//添加applytool
					arraylistApplyTools.add(new ApplyTool( i, j ,bitmap_apply_tools));
				}
			}
		}
		
		//构建激光路径
		for (int i = 0; i < mLaserEmitters.size(); i++) {
			mLaserEmitters.get(i).light();
		}
		
		cursor_col_start = cursor_col_target = 1;
		cursor_row_start = cursor_row_target = 1;

		setFeeX((cursor_col_start) * (GameMap.getSingleInstance().getCellWidth())
				+ (GameMap.getSingleInstance().getCellWidth() >> 1));
		setFeeY((cursor_row_start) * (GameMap.getSingleInstance().getCellHeight())
				+ (GameMap.getSingleInstance().getCellHeight() >> 1));

		targetX = getFeeX();
		targetY = getFeeY();

		playAnimation.setAction(GameConst.feeAction[fee_DirIndex]);
		
		// 加载音效
		int explodeSoundID[] = {R.raw.starexplode,R.raw.collectprops};
//		int soundID []= { R.raw.starexplode };
		GameMedia.loadSounds(explodeSoundID);

		// 播放音乐
		 GameMedia.playMusic("yinyue/backbg.ogg", true, true);
		 
			bitmap_wordBG = BitmapTool.getImageFromAssetFile("instruction.png");
		
			
		 GameWordButton gwb = new GameWordButton(GameWordButton.WordButtonFlag_Tutorial[0], bitmap_wordBG, 0, GameConst.SCR_H/3, bitmap_wordBG.getWidth(), bitmap_wordBG.getHeight(),"道具说明",ZiseLanguage.game_tutorial_content[GameMap.getSingleInstance().getLevel()][0]);
		 GameButtonManage.getInstance().addGameButton(gwb);
		 
		 
		 
		 //手勢識別
//		 mGestureDetector = new GestureDetector(gwb);
//		  this.setLongClickable(true); 
	        // setLongClickable( true )是必须的，因为 只有这样， 
	        // 我们当前的SurfaceView(view)才能够处理不同于触屏形式; 
	        // 例如：ACTION_MOVE，或者多个ACTION_DOWN 
//	        mGestureDetector.setIsLongpressEnabled(true); 
	        
		System.out.println("GameSurfaceView.Init_STATEGAME()");

	}

	private int getFeeCol()
	{
		return feeX/GameMap.getSingleInstance().getCellWidth();
	}
	
	private int getFeeRow()
	{
		return feeY/GameMap.getSingleInstance().getCellHeight();
	}
	
	
	private int apply_gamebuttonPos = 0;//记录gamebutton的位置
	private void AddApplyToolToToolbar()
	{
			for (int i = 0; i < arraylistApplyTools.size(); i++) {
				if(getFeeRow() == arraylistApplyTools.get(i).getApply_tool_row() && getFeeCol() == arraylistApplyTools.get(i).getApply_tool_col())
				{
					GameMedia.playSound(R.raw.collectprops,false);
					GameButtonManage.getInstance().addGameButton(new GameButton(arraylistApplyTools.get(i).getApplyKind(), bitmap_bar_select_button,arraylistApplyTools.get(i).getWhichToolBitmapByKind() ,
							bitmap_bar_select_button.getWidth()*apply_gamebuttonPos,  GameMap.getSingleInstance().getCellHeight() * GameMap.getSingleInstance().getMapH(), bitmap_bar_select_button.getWidth(), bitmap_bar_select_button.getHeight()));
					GameMap.getSingleInstance().SetNewElmentInMap(getFeeRow(), getFeeCol(),30);
				arraylistApplyTools.remove(i);
				apply_gamebuttonPos++;
				break;
				}
			}
	}
	

	// /////--------------------------------------------------
	// void setSoundLoop(boolean b_loop) {
	// mediaPlayer.setLooping(b_loop);
	// }
	//
	// void initSoundEffect(int effect_id) {
	// soundPoolEffect = new SoundPool(3, AudioManager.STREAM_MUSIC, 0);
	// soundeffectXiaoChuID = soundPoolEffect.load(context,
	// com.fs.zise.R.raw.efm, 1);
	// if (soundeffectXiaoChuID == 0)
	// System.out.println("加载失败");
	// }
	//
	// void playSoundEffect() {
	// int StreamID = soundPoolEffect.play(soundeffectXiaoChuID, 100, 100, 1,
	// 0, 1);
	// if (StreamID == 0)
	// System.out.println("播放流未成功");
	// }
	//
	// void initSound(int a_resid) {
	// mediaPlayer = MediaPlayer.create(context, a_resid);
	// mediaPlayer.setVolume(100, 100);
	// System.out.println("GameSurfaceView.initSound()");
	// }
	//
	// void playSound() {
	// try {
	// if (mediaPlayer != null) {
	// // mediaPlayer.start();
	// System.out.println("GameSurfaceView.playSound()");
	// }
	// } catch (Exception e) {
	// // TODO: handle exception
	// }
	// }
	//
	// void pauseSound() {
	// try {
	// if (mediaPlayer != null) {
	// mediaPlayer.pause();
	// System.out.println("GameSurfaceView.pauseSound()");
	// }
	// } catch (Exception e) {
	// // TODO: handle exception
	// }
	// }
	//
	// void stopSound() {
	// try {
	// if (mediaPlayer != null) {
	// mediaPlayer.stop();
	// mediaPlayer.release();
	// System.out.println("GameSurfaceView.stopSound()");
	// }
	// } catch (Exception e) {
	// // TODO: handle exception
	// }
	// }

	// 在surface的大小发生改变时激发
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
		System.out.println("GameSurfaceView.surfaceChanged()");
	}

	// 在surface创建时激发
	public void surfaceCreated(SurfaceHolder holder) {
		// System.out.println("surfaceCreated()--->" + this.getWidth());
		// System.out.println("surfaceCreated()--->" + this.getHeight());
		System.out.println("GameSurfaceView.surfaceCreated()");

		if (playAnimation == null)
			playAnimation = new Animation(new AnimationData("123.sprite",
					FeeBitmap));

		mbLoop = true;
		// 开启绘图线程
		new Thread(this).start();
	}

	// 在surface销毁时激发
	public void surfaceDestroyed(SurfaceHolder holder) {
		System.out.println("GameSurfaceView.surfaceDestroyed()");
		// 停止循环
		mbLoop = false;
	}

	CFPSMaker fpsMaker = new CFPSMaker();
	private boolean bInterrupt = false;

	// 绘图循环
	public void run() {
		fpsMaker.setNowFPS(System.nanoTime());
		while (mbLoop) {
			if (iClock < 65534)
				iClock++;
			else
				iClock = 0;

			lThreadTime = System.currentTimeMillis();

			if(!bInterrupt)
			synchronized (mSurfaceHolder) {

				OnDraw();
				Running();

				fpsMaker.makeFPS();

				try {
					Thread.sleep(40);
				} catch (Exception e) {
				}

				if (System.currentTimeMillis() - lThreadTime < SleepTime)
					Thread.yield();
			}

		}
	}

	int logo_index = 0;
	int game_counter = 0;
	private int menuCur; // 主菜单选项

	private void Running() {
		switch (gameState) {
		case GameConst.STATE_LOGO:
			logo_index++;
			if (logo_index > 10)
				gameState = GameConst.STATE_PREPARE;
			break;
		case GameConst.STATE_PREPARE:
			break;
		case GameConst.STATE_MAINMENU:
			break;
		case GameConst.STATE_GAME:
			
			
			// 当前小蜜蜂走完一个格子的时候再判断
			if (getFeeX() == targetX && getFeeY() == targetY) {
				// 更新目标位置
				if (!path.isEmpty()) {
					
					AddApplyToolToToolbar();
					
					BlockNode firstNode = (BlockNode) path.firstElement();
					int nextRow = firstNode.row;
					int nextColumn = firstNode.column;

					if (nextRow == (getFeeY() / GameMap.getSingleInstance().getCellHeight())
							&& nextColumn == (getFeeX() / GameMap.getSingleInstance().getCellWidth())) {
						path.removeElementAt(0);
						if (!path.isEmpty()) {
							firstNode = ((BlockNode) path.firstElement());
							nextRow = firstNode.row;
							nextColumn = firstNode.column;
						}else
						{
							System.out.println("path走完了");
						}
					}
					targetX = nextColumn * (GameMap.getSingleInstance().getCellWidth())
							+ (GameMap.getSingleInstance().getCellHeight() >> 1);
					targetY = nextRow * (GameMap.getSingleInstance().getCellHeight())
							+ (GameMap.getSingleInstance().getCellWidth() >> 1);
				}
			}

			MoveFee();

//			for (int i = 0; i < mBombs.size(); i++) {
//				if (mBombs.get(i).isBombExplosionOver()) { //爆炸结束，销毁炸弹
//					mBombs.remove(i);
//					System.out.println("GameSurfaceView.Running()--------");
//				}
//			}

			
			for (int i = 0; i < mLaserEmitters.size(); i++) {
				if(mLaserEmitters.get(i).getElementValueInLightPath(getFeeRow(), getFeeCol()))
				{
					feeDead = true;
					System.out.println("小蜜蜂遭遇激光");
					break;
				}
			
			}
			
			if(feeDead)
			{
				System.out.println("可怜的小蜜蜂挂了,重新开始游戏");
				Init_STATEGAME();
				break;
			}
			
			
			break;
		}
	}

	Button buttonContinue;
	Button buttonBackToMainMenu;

	// 绘图方法
	public void OnDraw() {
		// 锁定画布，得到canvas
		canvas = mSurfaceHolder.lockCanvas();

		if (mSurfaceHolder == null || canvas == null) {
			return;
		}
		// else {
		// if(g == null)
		// g = new Graphics(canvas);
		// }

		mPaint = new Paint();
		mPaint.setAntiAlias(true);
		mPaint.setColor(Color.BLACK);
		// 绘制矩形--清屏作用
		canvas.drawRect(0, 0, GameConst.SCR_W, GameConst.SCR_H, mPaint);

		switch (gameState) {
		case GameConst.STATE_LOGO:
			drawLogo();
			break;
		case GameConst.STATE_PREPARE:
			drawPrepare();
			break;
		case GameConst.STATE_MAINMENU:
			drawMainMenu();
			break;

		case GameConst.STATE_HELP:
			break;
		case GameConst.STATE_GAME:
			drawGame();
			break;
		case GameConst.STATE_LEVEL_SUCCESS:
			break;
		}

		canvas.clipRect(0, 0, GameConst.SCR_W, GameConst.SCR_H);
		drawFPS(fpsMaker.getFPS() + " FPS");

		// 绘制后解锁，绘制后必须解锁才能显示
		mSurfaceHolder.unlockCanvasAndPost(canvas);
	}

	
	private int buttonID = -1; //检测列表中哪个button被按下
	@Override
	public boolean onTouchEvent(MotionEvent event) {

		// int pointerCount = event.getPointerCount();
		// System.out.println("GameSurfaceView.onTouchEvent()="+pointerCount);

		touchX = event.getX();
		touchY = event.getY();

		switch (gameState) {
		case GameConst.STATE_LOGO:

			break;
		case GameConst.STATE_PREPARE:
			if (event.getAction() == MotionEvent.ACTION_DOWN) {
				if (isInRect(0, 0, GameConst.SCR_W, GameConst.SCR_H)) {
					gameState = GameConst.STATE_MAINMENU;

				}
			}
			break;

		case GameConst.STATE_MAINMENU:
			if (event.getAction() == MotionEvent.ACTION_DOWN) {

				/* 新游戏 */
				if (isInRect(0, 0, 480, 213)) {

					Init_STATEGAME();

					gameState = GameConst.STATE_GAME;
					// stopSound();
					// initSoundEffect(com.fs.zise.R.raw.efm);

				}

				/* 游戏帮助 */
				if (isInRect(200, 98 + 120 + 13 * 0, 320, 98 + 36 + 120 + 13
						* 1)) {

					if (menuCur == 1) {

//						@SuppressWarnings("deprecation")
//						final AbsoluteLayout absolute = new AbsoluteLayout(
//								ZiSeActivity.getActivity());
//						absolute.setBackgroundDrawable(new BitmapDrawable(
//								bgMenuBitmap));
//						helpScrollView = new ScrollView(
//								ZiSeActivity.getActivity());
//
//						TextView view = new TextView(ZiSeActivity.getActivity());
//						view.setTextSize(15); // 字体大小
//						view.setTextColor(Color.RED); // 设置淫荡颜色
//						view.setText(ZiseLanguage.help_str);
//						helpScrollView.addView(view);
//
//						// @SuppressWarnings("deprecation")
//						AbsoluteLayout.LayoutParams Relative = new AbsoluteLayout.LayoutParams(
//								GameConst.SCR_W-40 , 400, 20, 100); // X Y 宽 高
//						absolute.addView(helpScrollView, Relative);
//
//						ZiSeActivity.getActivity().setContentView(absolute);
//
//						Button button = new Button(ZiSeActivity.getActivity());
//						button.setText("确定");
//						Relative = new AbsoluteLayout.LayoutParams(
//								RelativeLayout.LayoutParams.WRAP_CONTENT,
//								RelativeLayout.LayoutParams.WRAP_CONTENT, 20,
//								400 + 110); // 这个button的位置随便你怎么设置
//						absolute.addView(button, Relative);
//						button.setOnClickListener(new OnClickListener() {
//							public void onClick(View v) {
//								ZiSeActivity
//										.getActivity()
//										.setContentView(
//												ZiSeActivity.getActivity().mGameSurfaceView);
//							}
//						});
					}

					menuCur = 1;
				}
			
			}
			break;

		case GameConst.STATE_HELP:
			if (event.getAction() == MotionEvent.ACTION_DOWN) {
				if (isInRect(0, GameConst.SCR_H - 40, 100, GameConst.SCR_H)) {
					System.out.println("DDDDDDDDDDDDD");
					gameState = GameConst.STATE_MAINMENU;
				}
			}
			break;

		case GameConst.STATE_GAME:
			
//			mGestureDetector.onTouchEvent(event);
			
			
			
			
			if (event.getAction() == MotionEvent.ACTION_DOWN) {
				
				buttonID = GameButtonManage.getInstance().onButtonPressed(touchX, touchY);
				if(buttonID == -1)	//无button被按下
					cursorLocate();
				else
				{
					
					System.out.println("QQQQQQQQQQQWWWWWWWWWWWWWWWWW ="+buttonID);
					if(GameButtonManage.getInstance().getGameButton(buttonID).getId() == GameWordButton.WordButtonFlag_Tutorial[0])
					{
						System.out.println(":cccccccqqqqw");
					}
				}
			} else if (event.getAction() == MotionEvent.ACTION_UP) {
				 if( buttonID != -1)
					 useTools();
				 
				 buttonID = -1;
			}
			 else if(event.getAction() == MotionEvent.ACTION_MOVE)
			 {
				 if( buttonID != -1)
					 GameButtonManage.getInstance().getGameButton(buttonID).OnButtonMoved(touchX, touchY);
				 else 
					 return false;
			 }
			break;

		}
		return true;
	}
	
	

	// //按键按下事件
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		// 上方向键
		case KeyEvent.KEYCODE_DPAD_UP:
			break;
		// 下方向键
		case KeyEvent.KEYCODE_DPAD_DOWN:
			// if (menuCur < 5) //菜单选项 --> menuCur
			// menuCur++;
			// else
			// menuCur = 0;
			break;

		case KeyEvent.KEYCODE_BACK:
			// ZiSeActivity.getActivity().finish();
			bInterrupt = true;
		 showExit();
			break;

		// case KeyEvent.KEYCODE_MENU:
		// break;
		}

		return true;
	}
	
	
	private boolean isShownExit = false;
	public void showExit() {
		if (!isShownExit) {
			AlertDialog.Builder builder = new AlertDialog.Builder(ZiSeActivity.getActivity());
			builder.setMessage("结束游戏吗?");
			builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					if (which == AlertDialog.BUTTON_POSITIVE) {
						System.gc();
						ZiSeActivity.getActivity().finish();
						System.exit(0);
						android.os.Process.killProcess(android.os.Process.myPid());
					}
				}
			});
			builder.setNegativeButton("否", new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					bInterrupt = false;
					dialog.dismiss();
					isShownExit = false;
				}
			});
			builder.setCancelable(false);
			builder.create().show();
			isShownExit = true;
		}
	}

	
	private int getMapRowByTouchEvent(float touchY)
	{
		if (touchY > GameMap.getSingleInstance().getCellHeight() * GameMap.getSingleInstance().getMapH() ) {
			System.out.println("按钮被拖动后放下超过地图范围Y");
			return -100;
		}
		
		for (int i = 0; i < GameMap.getSingleInstance().getMapH(); i++) {
			if (touchY > GameMap.getSingleInstance().getCellHeight() * i
					&& touchY < GameMap.getSingleInstance().getCellHeight() * (i + 1)) {
				return i;
			}
		}
		return -10;
	}
	
	private int getMapColByTouchEvent(float touchX)
	{
		for (int j = 0; j < GameMap.getSingleInstance().getMapW(); j++) {
			if (touchX > GameMap.getSingleInstance().getCellWidth() * j
					&& touchX < GameMap.getSingleInstance().getCellWidth() * (j + 1)) {
				return j;
			}
		}
		return -10;
	}
	
	private void  cursorLocate() {
		
		if (touchY > GameMap.getSingleInstance().getCellHeight() * GameMap.getSingleInstance().getMapH() ) {
			System.out.println("光标位置超过地图高度");
			return;
		}
		
		for (int i = 0; i < GameMap.getSingleInstance().getMapH(); i++) {
			if (touchY > GameMap.getSingleInstance().getCellHeight() * i
					&& touchY < GameMap.getSingleInstance().getCellHeight() * (i + 1)) {
				cursor_row_target = i;
			}
		}
		

		for (int j = 0; j < GameMap.getSingleInstance().getMapW(); j++) {
			if (touchX > GameMap.getSingleInstance().getCellWidth() * j
					&& touchX < GameMap.getSingleInstance().getCellWidth() * (j + 1)) {
				cursor_col_target =  j;
			}
		}

		System.out.println("cursor_row = " + cursor_row_target);
		System.out.println("cursor_col = " + cursor_col_target);

		if (GameMap.getSingleInstance().isNodCanPass(cursor_row_target, cursor_col_target)) { //节点可以通过
			// 根据蜜蜂位置 定位
			cursor_row_start = getFeeY() / GameMap.getSingleInstance().getCellHeight();
			cursor_col_start = getFeeX() / GameMap.getSingleInstance().getCellWidth();

			setPath(cursor_row_target, cursor_col_target);

		}
		
	}

	/**
	 * 设置游戏状态
	 */
	void setGameMode(int gameState) {
		this.gameState = gameState;
	}

	/**
	 * 得到游戏状态
	 * 
	 * @return
	 */
	int getGameMode() {
		return gameState;
	}

	private void drawFPS(String _string) {
		mPaint.setColor(Color.RED);
		canvas.drawText(fpsMaker.getFPS() + " FPS", 200, 700, mPaint);
	}

	private void drawLogo() {

		canvas.drawBitmap(logoBitmap, 0, 0, mPaint);

		// // /* 下一帧 */
		// mGifFrame.nextFrame();
		// /* 得到当前帧的图片 */
		// Bitmap b=mGifFrame.getImage();d
		//
		// /* 绘制当前帧的图片 */
		// if(b!=null)
		// canvas.drawBitmap(b,10,10,null);
		//
		// System.out.println("logo--->>");
	}

	private void drawPrepare() {
		canvas.drawBitmap(prepareBitmap, 0, 0, mPaint);
		Typeface typeface2 = Typeface.create("type1", Typeface.ITALIC);
		mPaint.setTypeface(typeface2);
		mPaint.setTextSize(20);
		mPaint.setColor(Color.YELLOW);
		mPaint.setTextAlign(Align.CENTER);
		canvas.drawText(ZiseLanguage.prepareString, GameConst.SCR_W / 2,
				GameConst.SCR_H - 30, mPaint);
	}

	private void drawMainMenu() {
		canvas.drawBitmap(bgMenuBitmap, 0, 0, mPaint);
		// Matrix matrix = new Matrix();
		// matrix.reset();
		// matrix.setRotate(10.0f);
		// matrix.postRotate(10.0f);
		// matrix.preRotate(10.0f);.
		// canvas.drawBitmap(bgMenuBitmap, matrix,mPaint);

		canvas.drawBitmap(bgMenuChoose,
				(GameConst.SCR_W - bgMenuItem.getWidth() >> 1) - 70,
				GameConst.SCR_H / 4 + 45 * menuCur, mPaint);

		for (int i = 0; i < 6; i++) {

			// canvas.clipRect(0, 80 + 32 * i, 320, 30 + (80 + 32*i));

			// canvas.save();
			// System.out.println("menuCur="+menuCur);
			// if (menuCur == i)
			// {
			// mPaint.setColor(Color.RED);
			// canvas.drawRect(70, 80+32*menuCur, 70+10, 10+80+32*menuCur,
			// mPaint);

			// canvas.drawBitmap(bgMenuChoose, (LlkConst.SCR_W -
			// bgMenuItem.getWidth() >> 1) - 70, 80 + 32 * i, mPaint);
			// System.out.println("menuCur ---->"+"00000");
			// }
			// canvas.restore();

			canvas.clipRect(
					GameConst.SCR_W - bgMenuItem.getWidth() >> 1,
					GameConst.SCR_H / 4 + 45 * i,
					bgMenuItem.getWidth()
							+ (GameConst.SCR_W - bgMenuItem.getWidth() >> 1),
					bgMenuItem.getHeight() / 6 + (GameConst.SCR_H / 4 + 45 * i),
					Region.Op.REPLACE);
			canvas.drawBitmap(bgMenuItem,
					GameConst.SCR_W - bgMenuItem.getWidth() >> 1,
					(GameConst.SCR_H / 4 + 45 * i) - bgMenuItem.getHeight() / 6
							* i, mPaint);

		}

		/*
		 * 椭圆形 canvas.clipRect(0, 0, LlkConst.SCR_W, LlkConst.SCR_H,
		 * Region.Op.REPLACE); RectF rF = new RectF(); rF.left = 100; rF.top =
		 * 200; rF.right = 350; rF.bottom = 350; mPaint.setColor(Color.DKGRAY);
		 * mPaint.setAlpha(20); canvas.drawOval(rF, mPaint);
		 */

		/*
		 * 按路径绘制 canvas.clipRect(0, 0, LlkConst.SCR_W, LlkConst.SCR_H,
		 * Region.Op.REPLACE); Path myPath = new Path(); myPath.moveTo(180,
		 * 300); myPath.lineTo(190, 150); myPath.lineTo(40,30);
		 * myPath.lineTo(20, 180); myPath.close();
		 * mPaint.setColor(Color.parseColor("#FFB6C1")); canvas.drawPath(myPath,
		 * mPaint);
		 */

		// /* 字体文件绘制字体
		// canvas.clipRect(0, 0, LlkConst.SCR_W, LlkConst.SCR_H,
		// Region.Op.REPLACE);
		// if(typeface1 == null)
		// {
		// typeface1 =
		// Typeface.createFromAsset(getResources().getAssets(),"fnt/font_text.ttf");
		// }
		// mPaint.setTextSize(50.0f);
		// mPaint.setTypeface(typeface1);
		// mPaint.setColor(Color.rgb(255, 255, 255));
		// canvas.drawText("woCa", LlkConst.SCR_W/4, LlkConst.SCR_H/4,mPaint);
		// */

		canvas.clipRect(0, 0, GameConst.SCR_W, GameConst.SCR_H,
				Region.Op.REPLACE);
		mPaint.setColor(Color.RED);
		canvas.drawText("X =" + touchX, 100, 400, mPaint);
		canvas.drawText("Y =" + touchY, 100, 430, mPaint);

		canvas.clipRect(0, 0, GameConst.SCR_W, GameConst.SCR_H);
	}

	// private float player_DestinationX = LlkConst.SCR_W >> 1;
	// private float player_DestinationY = LlkConst.SCR_H >> 1;
	// int playX = (int) player_DestinationX;
	// int playY = (int) player_DestinationY;

	final int fee_move_speed = 8;
	private int fee_DirIndex = 0;
	private int feeX;
	private int feeY;
	private boolean feeDead;

	Typeface typeface1, typeface2;
	
	
	private int startPoint = 0;//震动计数的起始点
	private boolean shake_switch = false;//震动开关
	private void shake(final int shake_time,int shake_W,int shake_H)//持续时间 //震动幅度(>0)
	{
		if(!isShake_switch())
			return ;
			
		
		System.out.println("GameSurfaceView.shake()");
		
		Matrix shakeMatrix = new Matrix();
		int eshalfhalf = shake_time/4;
		int eshalf = shake_time/2;	
		int eshalfOverhalf = shake_time/4*3;
		int real_shakeH = 0;
		int real_shakeW = 0;
		if(startPoint%2==0)
		{
			real_shakeH= -shake_H;
			real_shakeW = shake_W;
		}
		else
		{
			real_shakeH = shake_H;
			real_shakeW = -shake_W;
		}
		
		for (int i = startPoint; i < shake_time; i++) {
			 if( i>=0 && i< eshalfhalf)
			 {
				 shake_H = real_shakeH;
				 shake_W = real_shakeW;
				 startPoint = i;
				 break;
			 }
			 else if(i>=eshalfhalf&&i<eshalf)
			 {
				 shake_H = (real_shakeH)*2/3;
				 shake_W = (real_shakeW)*2/3;
				 startPoint = i;
				 break;
			 }
			 else if(i>=eshalf&&i<eshalfOverhalf)
			 {
				 shake_H = (real_shakeH)/3;
				 shake_W = (real_shakeW)/3;
				 startPoint = i;
				 break;
			 }
			 else if(i == shake_time-2)
			 {
				 shake_H = 0;
				 shake_W = 0;
				 startPoint = 0;//震动完毕后 归0
				 setShake_switch(false);
				 return;
			 }
		}
		if(startPoint<shake_time)
			startPoint++;
		shakeMatrix.setTranslate(shake_W, shake_H);
		canvas.setMatrix(shakeMatrix);
	}
	
	private void drawGame() {

		if(isShake_switch())
			shake(8,5,15);
		// if(typeface1 == null)
		// {
		// typeface1 =
		// Typeface.createFromAsset(getResources().getAssets(),"fnt/font_text.ttf");
		// }
		// mPaint.setTextSize(50.0f);
		// mPaint.setTypeface(typeface1);
		// mPaint.setColor(Color.rgb(255, 255, 255));
		// canvas.drawText("TABCDEFG", LlkConst.SCR_W/4, LlkConst.SCR_H/4,
		// mPaint);

		
		GameMap.getSingleInstance().DrawMap(canvas, mPaint, mapBitmap, GameMap.getSingleInstance().zise0_map0_one);

		for (int i = 0; i < mBombs.size(); i++) {
			mBombs.get(i).bomb_draw(canvas, mPaint);
		}

		for (int i = 0; i < mMirrors.size(); i++) {
			mMirrors.get(i).drawMirror(canvas, mPaint);
		}

		for (int i = 0; i < mLaserEmitters.size(); i++) {
			mLaserEmitters.get(i).drawLaserEmitter(canvas, mPaint);
			mLaserEmitters.get(i).drawLaser2(canvas, mPaint);
		}

		//绘制地图中的工具
		for (int i = 0; i < arraylistApplyTools.size();i++) {
			arraylistApplyTools.get(i).drawApplyTool(canvas, mPaint);
		}
		
		//绘制底部工具条
		BitmapTool.drawScale(canvas, mPaint, bitmap_bar_tool, GameConst.SCR_W, bitmap_bar_tool.getHeight() , 0, GameMap.getSingleInstance().getCellHeight()*GameMap.getSingleInstance().getMapH());
		//绘制放置于工具条上的button
		GameButtonManage.getInstance().OnButtonDraw(canvas, mPaint);
		
		//拖动ApplyButton的时候设置地图上对应块儿的阴影 ，但如果是 文字BUTTON的时候 则不需要绘制 阴影
		if(buttonID != -1 && GameButtonManage.getInstance().getGameButton(buttonID).getId() != GameWordButton.WordButtonFlag_Tutorial[0])
		{
			mPaint.setColor(R.color.fuchsia);
			canvas.drawRect(getMapColByTouchEvent(touchX)*GameMap.getSingleInstance().getCellHeight(),getMapRowByTouchEvent(touchY)*GameMap.getSingleInstance().getCellWidth(),
							getMapColByTouchEvent(touchX)*GameMap.getSingleInstance().getCellHeight()+GameMap.getSingleInstance().getCellWidth(),getMapRowByTouchEvent(touchY)*GameMap.getSingleInstance().getCellWidth()+GameMap.getSingleInstance().getCellHeight(), mPaint);
		}
		// int collisionfeeX =
		// playAnimation.getCollidesX(playAnimation.getFrame(),fee_DirIndex);
		// System.out.println("playAnimation.getFrame() ="+playAnimation.getFrame()+"collisionfeex = "+collisionfeeX);
		// int collisionfeeY =
		// playAnimation.getCollidesY(playAnimation.getFrame(),fee_DirIndex);
		// System.out.println("playAnimation.getFrame() ="+playAnimation.getFrame()+"collisionfeey = "+collisionfeeY);
		// int collisionfeeW =
		// playAnimation.getCollidesWidth(playAnimation.getFrame(),fee_DirIndex);
		// System.out.println("playAnimation.getFrame() ="+playAnimation.getFrame()+"collisionfeeW = "+collisionfeeW);
		// int collisionfeeH =
		// playAnimation.getCollidesHeight(playAnimation.getFrame(),fee_DirIndex);
		// System.out.println("playAnimation.getFrame() ="+playAnimation.getFrame()+"collisionfeeH = "+collisionfeeH);

		playAnimation.nextFrame();

		// System.out.println("getFeex() = "+ feeX);
		// System.out.println("getFeey() ="+ feeY);
		playAnimation.paint(canvas, mPaint, getFeeX(), getFeeY());

		// mPaint.setColor(Color.RED);
		// mPaint.setStyle(Style.STROKE);
		// canvas.drawRect(new Rect(feeX+collisionfeeX,feeY+collisionfeeY,
		// feeX+collisionfeeX+collisionfeeW,feeY+collisionfeeY+collisionfeeH),mPaint);

		drawCursor();

		//绘制蜜蜂路径轨迹
		mPaint.setColor(Color.GREEN);
		for (int i = 0; i < path.size(); i++) {
			BlockNode bNode = (BlockNode) path.elementAt(i);
			mPaint.setStyle(Style.FILL);
			canvas.drawRect(bNode.column * (GameMap.getSingleInstance().getCellWidth()), bNode.row* (GameMap.getSingleInstance().getCellHeight()),
					bNode.column* (GameMap.getSingleInstance().getCellWidth()) + (GameMap.getSingleInstance().getCellWidth()), bNode.row* (GameMap.getSingleInstance().getCellHeight()) + (GameMap.getSingleInstance().getCellHeight()),
					mPaint);
		}

		//字库
		fntPaint.drawFntWord(canvas, mPaint);
		
		
		
		
		// Path path = new Path();
		// path.moveTo(48+feeX, 48+feeY);
		// path.lineTo(48+feeX+30, 48+feeY);
		// path.lineTo(48+feeX+30,48+feeY+30);
		// path.lineTo(48+feeX, 48+feeY+30);
		// path.lineTo(48+feeX, 48+feeY);
		// path.close();
		// canvas.drawPath(path, mPaint);
		// mPaint.setStyle(Style.STROKE);
		// canvas.drawRect(48+feeX, 48+feeY, 48+feeX+feeW, 48+feeY+feeH,
		// mPaint);

	}

	private void MoveFee() {

		if (feeX < targetX && feeX > 0) {
			feeX += fee_move_speed;
		} else if (feeX > targetX && feeX < GameConst.SCR_W) {
			feeX -= fee_move_speed;
		}
		if (feeY < targetY && feeY > 0) {
			feeY += fee_move_speed;
		} else if (feeY > targetY && feeY < GameConst.SCR_H) {
			feeY -= fee_move_speed;
		}
		
	
	}

	
	// 定义路线
	private Vector path = new Vector();
	// 寻径算法
	private AAsterisk aasterisk = new AAsterisk();

	/**
	 * 设置dweep的行进路线
	 * 
	 * @param path
	 *            Vector
	 */
	public void setPath(int targetRow, int targetColumn) {

		System.out.println("setPath()--起点行"+ (cursor_row_start));
		System.out.println("setPath()--起点列"+ (cursor_col_start));
		System.out.println("setPath()--目标行" + (targetRow));
		System.out.println("setPath()--目标列" + (targetColumn));

		if (path.isEmpty()) {
			// 当路径列表为空时dweep处于不动状态，则从dweep当前位置开始寻路。
			aasterisk.find(cursor_row_start, cursor_col_start, targetRow,
					targetColumn, path);
			System.out.println("aaaaaaaaaa");
		} else {
			// 否则，则从路径的第一个节点重新开始寻路，该节点是目前dweep正在移向的节点。
			BlockNode node = (BlockNode) path.firstElement();
			aasterisk
					.find(node.row, node.column, targetRow, targetColumn, path);
			System.out.println("bbbbbbbbbbb");
		}
	}

	private int cursor_row_start;
	private int cursor_col_start;
	private int cursor_row_target;
	private int cursor_col_target;
	private int targetX;
	private int targetY;

	private void drawCursor() {
		canvas.clipRect(new Rect(0, 0, GameConst.SCR_W, GameConst.SCR_H));
		Matrix matrix = new Matrix();
		matrix.reset();
		matrix.setTranslate(GameMap.getSingleInstance().getCellWidth() * cursor_col_target,
				GameMap.getSingleInstance().getCellHeight() * cursor_row_target);
		canvas.drawBitmap(cursorBitmap, matrix, mPaint);
	}

	private float touchX, touchY;

	private boolean isInRect(int x1, int y1, int x2, int y2) {
		if (touchX > x1 && touchX < x2 && touchY > y1 && touchY < y2)
			return true;
		else
			return false;
	}

	public void setFeeY(int feeY) {
		this.feeY = feeY;
	}

	public int getFeeY() {
		return feeY;
	}

	public void setFeeX(int feeX) {
		this.feeX = feeX;
	}

	public int getFeeX() {
		return feeX;
	}

	private void useTools()
	{
			if(GameButtonManage.getInstance().getGameButton(buttonID) != null)
				GameButtonManage.getInstance().getGameButton(buttonID).OnButtonLeaved(touchX, touchY);
			
			boolean b_reSturct = false;
			//拖动的Gamebuton是 扳手的情况下,
			if(GameButtonManage.getInstance().getGameButton(buttonID) != null && GameButtonManage.getInstance().getGameButton(buttonID).getId() == ApplyTool.WRENCH)
			{
				//改变镜子方向
				System.out.println("MIRROR --R ="+getMapRowByTouchEvent(touchY));
				System.out.println("MIRROR --C ="+getMapColByTouchEvent(touchX));
			for (int i = 0; i < mMirrors.size(); i++) {
				if(mMirrors.get(i).getMirror(getMapRowByTouchEvent(touchY), getMapColByTouchEvent(touchX)))
					{
					b_reSturct = true;
					GameButtonManage.getInstance().getGameButton(buttonID).setVisible(false).setCanTouched(false);
					//更换镜子方向
					mMirrors.get(i).changeMirrorDir();
					break;
					}
				}
			//更换发射器方向
			for (int i = 0; i < mLaserEmitters.size(); i++) {
				if(mLaserEmitters.get(i).getLaserEmitter(getMapRowByTouchEvent(touchY), getMapColByTouchEvent(touchX)))
				{
					b_reSturct = true;
					GameButtonManage.getInstance().getGameButton(buttonID).setVisible(false).setCanTouched(false);
					mLaserEmitters.get(i).changeLaserEmitterDirectionAgainstClock();
					break;
				}
			}
			if(b_reSturct)
			{
				//重构发射器光线
				for (int i = 0; i < mLaserEmitters.size(); i++) {
					mLaserEmitters.get(i).light();
				}
				//由于重构了光线，判断炸弹是否处于光线上
				for (int i = 0; i < mBombs.size(); i++) {
					if (mBombs.get(i).explodeInLightPath()) {
						SetContinuousExplodeBombID(i);
					}
				}
			}
			
			}
			
			//拖动的Gamebuton是火柴
			if(GameButtonManage.getInstance().getGameButton(buttonID) != null && GameButtonManage.getInstance().getGameButton(buttonID).getId() == ApplyTool.MATCHES)
			{
				for (int i = 0; i < mBombs.size(); i++) { //火柴按鈕抬起時候看釋放的位置是第？格蛋
					if(mBombs.get(i).getBomb(getMapRowByTouchEvent(touchY), getMapColByTouchEvent(touchX)))
					{
						GameButtonManage.getInstance().getGameButton(buttonID).setVisible(false).setCanTouched(false);
						SetContinuousExplodeBombID(i);
					}
				}
			}
			
			System.out.println("Button抬起时的Row ="+getMapRowByTouchEvent(touchY));
			System.out.println("Button抬起时的Col ="+getMapColByTouchEvent(touchX));	
	
	}
	/**
	 * 
	 * 九宮格连环触发机制
	 * @param orgid  触发点ID
	 */
	private  void SetContinuousExplodeBombID(int orgid)
	{
		Vector<Integer> eh = new Vector<Integer>();
		Vector<Integer> ef = new Vector<Integer>();//最終可爆炸蛋ID 集合
		
		eh.add(orgid);
		//根據 初始ID 連環搜索 炸彈ID
		while(eh.size()>0)
		{
			for (int m = 0; m < mBombs.size(); m++) {
				if(mBombs.get(eh.firstElement()).searchExplodeRange(mBombs.get(m).getBomb_row(),mBombs.get(m).getBomb_col()))
				{
					if(!ef.contains(m))
						eh.add(m);
				}
			}
			
			for (int l= 0; l < eh.size(); l++) {
				if(!ef.contains(eh.get(l)))//排除添加  在eh里与ef中已有的相同元素到ef
					ef.add(eh.get(l));//元素值拷貝
			}
			eh.remove(0);
		}
		
		//根據最終得到的炸彈結合 依次設置炸彈。
		if(ef.size()>0)
		{
			for (int k = 0; k < ef.size();k++) {
				mBombs.get(ef.get(k)).setBOMB_STATE(Bombs.STATE_EXPLOSION);
				if(mBombs.get(ef.get(k)).searchExplodeRange(getFeeRow(),getFeeCol()))
					{
						feeDead = true;
						System.out.println("小蜜蜂遭遇炸弹9宫格波");
					}
			}
			//打开震动
			setShake_switch(true);
			// 播放音效
			GameMedia.playSound(R.raw.starexplode, false);
		}
	}
	
	private void clearAllRescoures()
	{
		apply_gamebuttonPos = 0;
		path.clear();
		mBombs.clear();
		mMirrors.clear();
		mLaserEmitters.clear();
		GameButtonManage.getInstance().clearAllGameButton();
	}

	public void setShake_switch(boolean shake_switch) {
		this.shake_switch = shake_switch;
	}

	public boolean isShake_switch() {
		return shake_switch;
	}
	
}
